/*
 * @Author: 彭林
 * @Date: 2021-06-21 15:55:57
 * @LastEditTime: 2021-06-22 09:13:46
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/api/v1/wechat.go
 */
package v1

import (
	"saas-app/app/define"
	"saas-app/library/cache"
	"saas-app/library/response"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func Verification(r *ghttp.Request) {

	var data *define.MessageEntity
	token := g.Cfg().GetString("wechat.token")

	if err := r.Parse(&data); err != nil {
		r.Response.WriteExit(false)
		r.Exit()
	}

	result := data.CheckSignature(token)
	if result {
		r.Response.WriteExit(data.EchoStr)
	} else {
		r.Response.WriteExit(false)
	}
}

/**
 * @description: 获取微信access_token
 * @param {*ghttp.Request} r
 * @return {*}
 */
func GetAccessToken() {
	appid := g.Cfg().GetString("wechat.appid")
	appsecret := g.Cfg().GetString("wechat.appsecret")
	var token *define.WechatAccessToken
	if err := g.Client().GetVar("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret).Scan(&token); err != nil {
		panic(err)
	} else {
		cache.Set("wechat_access_token", token.AccessToken, 0)
		g.Log().Info("获取微信access_token:" + token.AccessToken)
	}
}

func B2S(bs []uint8) string {
	ba := []byte{}
	for _, b := range bs {
		ba = append(ba, byte(b))
	}
	return string(ba)
}

func TestRedis(r *ghttp.Request) {
	// re, _ := cache.Do("SETEX", "cache_user_id", 6000, 10086)
	// item := []int{1, 2, 3, 4, 5, 6, 7}
	re, _ := cache.Do("SADD", "bbs", "discuz.net", "groups.google.com")
	// re = B2S(re.([]uint8))
	response.JsonExit(r, 0, "ok", re)
}
